package com.njh.check.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hos.entity.his.*;
import com.hos.entity.sys.User;
import com.hos.utils.IdGeneratorUtil;
import com.hos.utils.WebUtil;
import com.hos.vo.CheckingResultImgVo;
import com.njh.check.feigns.UserFeign;
import com.njh.check.mapper.CareHistoryMapper;
import com.njh.check.mapper.CareOrderItemMapper;
import com.njh.check.mapper.CareOrderMapper;
import com.njh.check.mapper.CheckResultMapper;
import com.njh.check.service.CheckService;
import com.njh.check.vo.CheckQueryParamsVo;
import com.njh.check.vo.CheckingVo;
import com.njh.check.vo.NewCheckReturnVo;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author ：njh
 * @date ：Created in 2023/12/19 9:35
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class CheckServiceImpl implements CheckService {

    @Resource
    private CheckResultMapper checkResultMapper;
    @Resource
    private CareOrderItemMapper careOrderItemMapper;
    @Resource
    private CareOrderMapper careOrderMapper;
    @Resource
    private CareHistoryMapper careHistoryMapper;
    @Resource
    private UserFeign userFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Page<CheckResult> queryAllCheckResultForPage(CheckQueryParamsVo queryParams) {
//
//      测试mybatisplus存取json
//
//        List list=new ArrayList();
//        CheckingResultImgVo cr=new CheckingResultImgVo();
//        cr.setName("n1");
//        cr.setUrl("u1");
//        list.add(cr);
//        CheckingResultImgVo cr2=new CheckingResultImgVo();
//        cr2.setName("n2");
//        cr2.setUrl("u2");
//        list.add(cr2);
//        System.out.println("list:"+list);
//
//
//        UpdateWrapper<CheckResult> wrapper=new UpdateWrapper();
//        wrapper.lambda()
//                .set(CheckResult::getResultImg, JSONUtil.toJsonStr(list))
////                .set(CheckResult::getResultImg, list)
//                .eq(CheckResult::getCocId,"ITEM1494211265868988416");
//        int update = checkResultMapper.update(wrapper);
//        System.out.println("update"+update);
//
//        List<CheckResult> checkResults = checkResultMapper.selectList(null);
//        for (CheckResult c :
//                checkResults) {
//            System.out.println(c);
//        }
//        return null;


        // 设置分页参数
        Page<CheckResult> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());

        LambdaQueryWrapper<CheckResult> wrapper = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (queryParams.getCheckItemIds().size() > 0) {
            wrapper.in(CheckResult::getCheckItemId, queryParams.getCheckItemIds());
        }
        if (StringUtils.hasText(queryParams.getRegId())) {
            wrapper.eq(CheckResult::getRegId, queryParams.getRegId());
        }
        if (StringUtils.hasText(queryParams.getPatientName())) {
            wrapper.like(CheckResult::getPatientName, queryParams.getPatientName());
        }

        return this.checkResultMapper.selectPage(page, wrapper);
    }

    @Override
    public List<CareOrderItem> queryNeedCheckItem(CheckQueryParamsVo queryParams) {

        LambdaQueryWrapper<CareOrderItem> wrapper = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (queryParams.getCheckItemIds().size() > 0) {
            wrapper.in(CareOrderItem::getItemRefId, queryParams.getCheckItemIds());
        }

        // 查询已经付款和待完成的
        wrapper.eq(CareOrderItem::getItemType, 1);
        wrapper.eq(CareOrderItem::getStatus, 1);
        return careOrderItemMapper.selectList(wrapper);

    }

    @Override
    public NewCheckReturnVo queryCheckItemByItemId(String itemId) {

        LambdaQueryWrapper<CareOrderItem> wrapper = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (StringUtils.hasText(itemId)) {
            wrapper.eq(CareOrderItem::getItemId, itemId);
        }
        CareOrderItem careOrderItem = careOrderItemMapper.selectOne(wrapper);


        // 根据CareOrderItem的co_id查询CareOrder
        LambdaQueryWrapper<CareOrder> wrapper2 = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (StringUtils.hasText(careOrderItem.getCoId())) {
            wrapper2.eq(CareOrder::getCoId, careOrderItem.getCoId());
        }
        CareOrder careOrder = careOrderMapper.selectOne(wrapper2);


        // 根据CareOrder的ch_id查询CareHistory
        LambdaQueryWrapper<CareHistory> wrapper3 = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (StringUtils.hasText(careOrder.getChId())) {
            wrapper3.eq(CareHistory::getChId, careOrder.getChId());
        }
        CareHistory careHistory = careHistoryMapper.selectOne(wrapper3);


        NewCheckReturnVo newCheckReturnVo = new NewCheckReturnVo(careOrderItem, careOrder, careHistory);

        return newCheckReturnVo;
    }

    @Override
    public Integer startCheck(String itemId) {

        // careorderitem的status改成3（代表已完成状态）
        UpdateWrapper<CareOrderItem> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 3);
        wrapper.eq("item_id", itemId);
        int update = careOrderItemMapper.update(wrapper);

        CareOrderItem careOrderItem = careOrderItemMapper.selectById(itemId);


        // 根据CareOrderItem的co_id查询CareOrder
        LambdaQueryWrapper<CareOrder> wrapper2 = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (StringUtils.hasText(careOrderItem.getCoId())) {
            wrapper2.eq(CareOrder::getCoId, careOrderItem.getCoId());
        }
        CareOrder careOrder = careOrderMapper.selectOne(wrapper2);
        // 根据CareOrder的ch_id查询CareHistory
        LambdaQueryWrapper<CareHistory> wrapper3 = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (StringUtils.hasText(careOrder.getChId())) {
            wrapper3.eq(CareHistory::getChId, careOrder.getChId());
        }
        CareHistory careHistory = careHistoryMapper.selectOne(wrapper3);


        // 新建checkresult
        CheckResult checkResult = new CheckResult();
        checkResult.setCocId(itemId);
        checkResult.setCheckItemId(Integer.parseInt(careOrderItem.getItemRefId()));
        checkResult.setCheckItemName(careOrderItem.getItemName());
        checkResult.setPrice(careOrderItem.getPrice());
        checkResult.setRegId(careHistory.getRegId());
        checkResult.setResultMsg(null);
        checkResult.setResultImg(null);
        checkResult.setPatientId(careOrder.getPatientId());
        checkResult.setPatientName(careOrder.getPatientName());
        checkResult.setResultStatus("0");
        checkResult.setCreateTime(new Date());
        checkResult.setUpdateTime(null);
        checkResult.setCreateBy(getUserByToken().getUserName());
        checkResult.setUpdateBy(null);
        int insert = checkResultMapper.insert(checkResult);

        return insert;
    }

    @Override
    public Page<CheckResult> queryAllCheckingResultForPage(CheckQueryParamsVo queryParams) {

        // 设置分页参数
        Page<CheckResult> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());

        LambdaQueryWrapper<CheckResult> wrapper = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (queryParams.getCheckItemIds().size() > 0) {
            wrapper.in(CheckResult::getCheckItemId, queryParams.getCheckItemIds());
        }
        if (StringUtils.hasText(queryParams.getRegId())) {
            wrapper.eq(CheckResult::getRegId, queryParams.getRegId());
        }
        if (StringUtils.hasText(queryParams.getPatientName())) {
            wrapper.like(CheckResult::getPatientName, queryParams.getPatientName());
        }
        wrapper.eq(CheckResult::getResultStatus, 0);

        return this.checkResultMapper.selectPage(page, wrapper);
    }

    @Override
    public Integer completeCheckResult(CheckingVo checkingVo) {

        ObjectMapper mapper = new ObjectMapper();

        System.out.println(checkingVo.getResultImg());

        UpdateWrapper<CheckResult> wrapper = new UpdateWrapper();
        wrapper.lambda()
                .set(CheckResult::getResultMsg, checkingVo.getResultMsg())
                .set(CheckResult::getResultImg, JSONUtil.toJsonStr(checkingVo.getResultImg()))
//                .set(CheckResult::getResultImg, mapper.writeValueAsString(checkingVo.getResultImg()))

                // 改状态表示已完成
                .set(CheckResult::getResultStatus, 1)
                .eq(CheckResult::getCocId, checkingVo.getItemId());
        int update = checkResultMapper.update(wrapper);

        return update;
    }


    /**
     * @return com.hos.entity.sys.User
     * @create by: 陈海彬
     * @description: 获取请求用户的信息
     * @create time: 2023/12/12 10:39
     */
    private User getUserByToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        return userFeign.selectUserByPhone(phone);
    }

}